package cn.ahut.test2;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class MyBeanPostProcesser implements BeanPostProcessor{

	/**
	 * bean:配置的实例对象
	 * beanName：配置文件中配置的类的标识
	 */
	@Override
	public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException {
		System.out.println("第八步：在初始化后执行");
		
		if(beanName.equals("product")){
			//return之前可以做一些增强
			Object proxy = Proxy.newProxyInstance(bean.getClass().getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler(){
				@Override
				public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
					if("add".equals(method.getName())){
						System.out.println("add方法被增强了");
						Object result  = method.invoke(bean, args);
						 return result;
					}
					return method.invoke(bean, args);
				}
			});
			return proxy;
		}
		return bean;
	}

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		System.out.println("第五步：在类初始化完成之前执行");
		return bean;
	}

}
